package lew.bing.tom;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;

@Slf4j
public class GlobalServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private HtmlHandler htmlHandler;

    public GlobalServlet(HtmlHandler htmlHandler) {
        this.htmlHandler = htmlHandler;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        final String requestURI = request.getRequestURI();
        if (requestURI.endsWith("html") ||
                requestURI.endsWith("htm")) {
            // 对于html通过匹配到真实的
            htmlHandler(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            response.setHeader("Server", "Embedded Tomcat");
            try (Writer writer = response.getWriter()) {
                writer.write("Hello, Embedded Tomcat!");
                writer.flush();
            }
        }

    }

    private void htmlHandler(HttpServletRequest request,
                             HttpServletResponse response
                             ) {
        htmlHandler.handler(request, response);
    }

}
